<?php

namespace app\zyhsapi\model\good_rtc_live;

use app\chat\LiveMessage as ChatLiveMessage;
use app\common\cachemodel\ZlcrAstr;
use app\common\lib\Aes;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\zyhsapi\model\BaseCacheZyhs;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsGoodRtcLiveRecord extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_good_rtc_live_record';

    protected $cacheModel = 'zyhs.good_rtc_live_record';

    /**
     * 更新信息
     * @param int $liveReocrdId
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $liveReocrdId, array $data)
    {
        try
        {
            $this->where(['id' => $liveReocrdId])->update($data);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $liveReocrdId)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 获取优质连线直播间最新的直播记录
     * @return int
     * @throws \Exception
     */
    public function getNewestRecordId($appType)
    {
        $data = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)
            ->getDataAndSet(function ()
            {
                try
                {
                    return $this->where('status', 1)->order('id', 'DESC')->field('*')->findOrFail()->toArray();
                }
                catch (\Exception $e)
                {
                    return 0;
                }
            }, [], 'new_record_id');
        $id = 0;
        if ($data)
        {
            $extend = json_decode($data['extend'], true);
            if (isset($extend['app_type']) && in_array($appType, $extend['app_type'], false))
            {
                $id = (int)$data['id'];
            }
        }
        return $id;
    }

    /**
     * 批量获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            $res = $this->whereIn('id', $ids)->order('id', 'DESC')->column('status,base_num,current_mid,start_play_time,msg_num1,msg_num2,user_num,start_aid,start_time,end_aid,end_time,extend', 'id');
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }

        return $res;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'status', 'base_num', 'current_mid', 'start_play_time', 'msg_num1', 'msg_num2', 'user_num', 'start_aid', 'start_time', 'end_aid', 'end_time']);
            if (isset($data['extend']))
            {
                $data[$index]['extend'] = json_decode($data['extend'], true);
            }
        }

        return $data;
    }

    /**
     * 获取 播放录音音频信息
     * @param array $recordInfo
     * @param int $mid
     * @param int $appType 1=>准有好事 2=>准了APP
     * @return array
     * @throws \Exception
     */
    public function getPlayAudioInfo(array $recordInfo, int $mid = 0, int $appType = 1)
    {
        $mid = $mid ?: $recordInfo['current_mid'];
        $mediaInfo = (new ZyhsGoodRtcLiveMedia())->getInfoById($mid);
        $astrInfo = (new ZlcrAstr())->getInfoById($mediaInfo['astr_id'], ['avatar', 'nickname']);

        if ($mid !== $recordInfo['current_mid'])
        {
            $startDuration = 0;
        } else
        {
            $startDuration = time() - $recordInfo['start_play_time'];
        }
        return [
            'audio' => $mediaInfo['vid'] ? (new Aes())->encryptWithOpenssl($mediaInfo['vid'], $appType === 1 ? 'zyhsapp' : 'app') : '',
            'duration' => $mediaInfo['duration'],
            'start_duration' => $startDuration,
            'live_avatar' => $astrInfo['avatar'],
            'live_name' => $astrInfo['nickname'],
            'user_avatar' => $mediaInfo['avatar'],
            'user_name' => $mediaInfo['nickname'],
            'astr_id' => $mediaInfo['astr_id'],
            'bg_img' => $mediaInfo['bg_img'],
            'id' => $mediaInfo['id'],
        ];
    }

    /**
     * 获取历史弹幕数据
     * @param int $liveRecordId
     * @return array
     * @throws \Exception
     */
    public function getHistoryMsgData(int $liveRecordId)
    {
        $sendMsgRecord = CacheManageZyhs::getInstance()->redisHandler->lRange('good_rtc_live:send:msg:record:' . $liveRecordId, 0, -1);
        $sendMsgHistoryList = [];
        if (!empty($sendMsgRecord))
        {
            for ($i = count($sendMsgRecord) - 1; $i >= 0; $i--)
            {
                $sendMsgHistoryList[] = json_decode($sendMsgRecord[$i], true);
            }
        }

        return $sendMsgHistoryList;
    }

    /**
     * 获取 在线人数
     * @param int $liveRecordId
     * @return int
     */
    public function getOnlineNum(int $liveRecordId)
    {
        try
        {
            // 实际在线人数
            $onlineUserNum = ChatLiveMessage::getClientIdCountByGroup('zyhs_good_rtc_live_room_' . $liveRecordId);
        }
        catch (\Exception $e)
        {
            $onlineUserNum = 0;
        }

        return $onlineUserNum;
    }

    /**
     * 添加同步在线人数队列
     * @param int $liveRecordId
     * @return void
     * @throws ApiException
     * @throws \RedisException
     */
    public function addSyncOnlineNumQueue(int $liveRecordId)
    {
        $redis = CacheManageZyhs::getInstance()->redisHandler;
        $cacheKey = 'zyhs_cache:good_rtc_live:sync_online_num:' . $liveRecordId;
        $num = $redis->incr($cacheKey);
        if ($num === 1)
        {   // 添加队列
            Util::queuePush('zyhs_good_rtc_live_sync_online_num', [
                'live_record_id' => $liveRecordId,
            ], 1);

            $redis->expire($cacheKey, 2);
        }
    }
}
